<?php

namespace frame\lib;

class Captcha
{
    private $width = 100;
    private $height = 40;
    private $code;
    private $image;
    public function __construct($width = 100, $height = 40, $length = 4)
    {
        $this->width = $width;
        $this->height = $height;
        $this->code = $this->generateCode($length);
        $this->image = $this->createImage();
    }

    private function generateCode($length)
    {
        $characters = '123456789';
        $charactersLength = strlen($characters);
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $characters[rand(0, $charactersLength - 1)];
        }
        return $code;
    }

    private function createImage()
    {
        $image = imagecreatetruecolor($this->width, $this->height);
        $white = imagecolorallocate($image, 255, 255, 255);
        $black = imagecolorallocate($image, 0, 0, 0);
        $gray = imagecolorallocate($image, 200, 200, 200);
        $bgColor = imagecolorallocate($image, 220, 220, 220);
        imagefilledrectangle($image, 0, 0, $this->width, $this->height, $bgColor);
        for ($i = 0; $i < 100; $i++) {
            imagesetpixel($image, rand(0, $this->width), rand(0, $this->height), $gray);
        }
        $fontSize = 5;
        $x = (imagesx($image) - imagefontwidth($fontSize) * strlen($this->code)) / 2;
        $y = intval((imagesy($image) - imagefontheight($fontSize)) / 2);
        imagestring($image, $fontSize, $x, $y, $this->code, $black);

        for ($i = 0; $i < 5; $i++) {
            imageline($image, rand(0, $this->width), rand(0, $this->height), rand(0, $this->width), rand(0, $this->height), $gray);
        }
        header('Content-Type: image/png');
        imagepng($image);
        imagedestroy($image);
        $_SESSION['captcha_code'] = $this->code;
        return $this->code;
    }

    public function getCode()
    {
        return $this->code;
    }
}


// Usage example
// $captcha = new Captcha();
